package com.orkasgb.framework.springsecurity.sms;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * OrkasgbSMSAuthencationFilter类在启用了Spring Security的应用程序中实现了一个定制的基于SMS的身份验证过滤器。
 * 它检查带有所需参数的POST请求，创建身份验证令牌，如果成功，则返回经过身份验证的用户对象。
 *
 * @date Sep 21, 2010 4:21:21 PM
 * @since 0.0.5
 */
@Component
public class OrkasgbSMSAuthencationFilter extends AbstractAuthenticationProcessingFilter {

    /**
     * 自定义请求路经为"/codeLogin"，请求方式为POST
     */
    private static final AntPathRequestMatcher DEFAULT_ANT_PATH_REQUEST_MATCHER = new AntPathRequestMatcher("/codeLogin",
            "POST");

    /**
     * 构造函数，构造是时需要做以下操作：
     * <ol>
     *    1. 设置需要身份验证的请求路径为DEFAULT_ANT_PATH_REQUEST_MATCHER；
     *    2. 设置身份验证过滤器的匹配器，因为使用的还是默认的ProviderManager实现，所有需要手动将Provider替换为自定义的
     *       OrkasgbSMSAuthenticationProvider；
     * </ol>
     */
    public OrkasgbSMSAuthencationFilter() {
        super(DEFAULT_ANT_PATH_REQUEST_MATCHER);
        OrkasgbSMSAuthenticationProvider orkasgbSMSAuthenticationProvider =
                new OrkasgbSMSAuthenticationProvider();
        ProviderManager providerManager = new ProviderManager(orkasgbSMSAuthenticationProvider);
        // 这里必须调用手动设置下providerManager，否则会使用默认的，那么最终几不会走到自定义的SMS身份验证过滤器的代码块中。
        this.setAuthenticationManager(providerManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }

        String phoneNumber = request.getParameter("phoneNumber");
        String code = request.getParameter("code");

        // 此处构造的是一个还未认证的OrkasgbSMSAuthenticationToken，即里面的authenticated属性为false。
        OrkasgbSMSAuthenticationToken orkasgbSMSAuthenticationToken = new OrkasgbSMSAuthenticationToken(phoneNumber, code);
        setDetails(request, orkasgbSMSAuthenticationToken);
        // 认证方式委托为providerManager，providerManager又会委托给orkasgbSMSAuthenticationProvider来执行身份验证。
        return this.getAuthenticationManager().authenticate(orkasgbSMSAuthenticationToken);
    }

    @Override
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    protected void setDetails(HttpServletRequest request, OrkasgbSMSAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }

    @Override
    public void setSecurityContextRepository(SecurityContextRepository securityContextRepository) {
        super.setSecurityContextRepository(securityContextRepository);
    }
}
